package com.honey.mamabike.user.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.honey.mamabike.cache.CommonCacheUtil;
import com.honey.mamabike.common.exception.MaMaBikeException;
import com.honey.mamabike.security.AESUtil;
import com.honey.mamabike.security.Base64Util;
import com.honey.mamabike.security.MD5Util;
import com.honey.mamabike.security.RSAUtil;
import com.honey.mamabike.user.dao.UserMapper;
import com.honey.mamabike.user.entity.User;
import com.honey.mamabike.user.entity.UserElement;
import com.honey.mamabike.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by setsun on 2017/10/10.
 */
@Service
@Slf4j
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommonCacheUtil cacheUtil;

    @Override
    public String login(String data, String key) throws MaMaBikeException {
        String token = null;
        String decryptData = null;
        try {
            byte[] aesKey = RSAUtil.decryptByPrivateKey(Base64Util.decode(key));    //解密key
            System.out.println(aesKey);
            decryptData = AESUtil.decrypt(data,new String(aesKey,"UTF-8")); //解密value
            System.out.println(decryptData);
            if (decryptData == null){
                throw new Exception();
            }
            JSONObject jsonObject = JSON.parseObject(decryptData);
            String mobile = jsonObject.getString("mobile");
            String code = jsonObject.getString("code");
            String platform = jsonObject.getString("platform");
            if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code)){
                throw new Exception();
            }
            //去redis 取验证码 比较手机号码和验证码是否匹配 验证码存在过期特性
            String verCode = cacheUtil.getCacheValue(mobile);
            User user;
            if (code.equals(verCode)){
                //手机验证码匹配
                user = userMapper.selectByMobile(mobile);
                if (user == null){
                    user = new User();
                    user.setMobike(mobile);
                    user.setNickname(mobile);
                    userMapper.insertSelective(user);
                }
            }else{
                throw new MaMaBikeException("手机号验证码不匹配");
            }

            try {
                //生成token
                token = generateToken(user);

            } catch (Exception e) {
                throw new MaMaBikeException("生成token失败");
            }
            UserElement userElement = new UserElement();
            userElement.setMobile(mobile);
            userElement.setUserId(user.getId());
            userElement.setToken(token);
            userElement.setPlatform(platform);
            cacheUtil.putTokenWhenLogin(userElement);
        }catch (Exception e){
            log.error("Fail to decrypt data ",e);
            throw new MaMaBikeException("数据解析出错");

        }
        return token;
    }

    @Override
    public void modifyNickName(User user) throws MaMaBikeException {
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     *
     * @param user
     * @return 生成token
     */
    private String generateToken(User user) {

        String source = user.getId()+":"+user.getMobike()+":"+System.currentTimeMillis();
        return MD5Util.getMD5(source);
    }


}
